package com.steam.pet.service.impl;

import com.steam.basic.exception.BusinessException;
import com.steam.basic.service.IBaiduAiAuditService;
import com.steam.basic.service.impl.BaseServiceImpl;
import com.steam.basic.util.*;
import com.steam.order.domain.OrderPetAcquisition;
import com.steam.order.mapper.OrderPetAcquisitionMapper;
import com.steam.order.rocket.DelayProduce;
import com.steam.org.domain.Employee;
import com.steam.org.domain.Shop;
import com.steam.org.mapper.EmployeeMapper;
import com.steam.org.mapper.ShopMapper;
import com.steam.pet.domain.Pet;
import com.steam.pet.domain.SearchMasterMsg;
import com.steam.pet.domain.SearchMasterMsgAuditLog;
import com.steam.pet.mapper.PetMapper;
import com.steam.pet.mapper.SearchMasterMsgAuditLogMapper;
import com.steam.pet.mapper.SearchMasterMsgMapper;
import com.steam.pet.query.SearchMasterMsgQuery;
import com.steam.pet.service.ISearchMasterMsgService;
import com.steam.user.domain.Logininfo;
import com.steam.user.domain.User;
import com.steam.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 业务实现类：
 */
@Service
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements ISearchMasterMsgService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;
    @Autowired
    private IBaiduAiAuditService baiduAiAuditService;
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;
    @Autowired
    private PetMapper petMapper;
    @Autowired
    private DelayProduce delayProduce;

    @Override
    public AjaxResult publish(SearchMasterMsg msg, HttpServletRequest request) {
        Logininfo logininfo = LoginContext.getLogininfo(request);
        User user = userMapper.loadByLogininfoId(logininfo.getId());
        msg.setUserId(user.getId());
        msg.setState(0);//待审核 - 可以不设置
        //2.将寻主消息添加到数据库- 如何审核失败 - 修改寻主消息重新审核【shop_id】
        searchMasterMsgMapper.save(msg); //自增ID
        //3.百度AI智能审核  //地址最后不好审核
        Boolean boo1 = baiduAiAuditService.textAudit(msg.getName() + msg.getTitle());
        Boolean boo2 = baiduAiAuditService.imageAudit(msg.getResources());
        //3.1.审核成功
        if(boo1 && boo2){//成功
            //a.修改状态：0 - 1
            msg.setState(1);//审核通过待处理
            //b1.找到最近的店铺 - 分配店铺【设置到shopId】 - 发送短信给店铺管理员，告诉他去接回宠物
            List<Shop> shops = shopMapper.loadAll();
            Point point = DistanceUtils.getPoint(msg.getAddress());//用户发布寻主消息的地址 - 宠物的地址
            Shop nearestShop = DistanceUtils.getNearestShop(point, shops);
            //b2.找到店铺 - 绑定店铺 。没有周到就放到寻主池[state=1,shopId=null]
            if(nearestShop!=null){
                msg.setShopId(nearestShop.getId());
            }
            //b3.更新数据库
            searchMasterMsgMapper.update(msg);
            //c.添加审核成功日志
            SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
            log.setMsgId(msg.getId());
            log.setState(1);//审核成功
            //百度智能审核
            log.setNote("审核成功");
            searchMasterMsgAuditLogMapper.save(log);
            if(nearestShop!=null){
                Employee employee = employeeMapper.loadByShopId(nearestShop.getId());
                //SmsUtils.sendSms(employee.getPhone(),"你有新的订单，请去"+msg.getAddress()+"接回宠物!!!");
                System.out.println("你有新的订单，请去"+msg.getAddress()+"接回宠物!!!");
            }
            return new AjaxResult();
        }else{
            //3.2.审核失败
            //a.添加审核失败日志
            SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
            log.setMsgId(msg.getId());
            log.setState(0);//审核失败
            //百度智能审核
            log.setNote("审核失败");
            searchMasterMsgAuditLogMapper.save(log);
            //b.发送短信给用户告诉他审核失败，修改寻主消息
            //SmsUtils.sendSms(user.getPhone(),"你发布的寻主消息未通过审核，请修改之后重新发布!!!");
            System.out.println("你发布的寻主消息未通过审核，请修改之后重新发布!!!");
            return AjaxResult.me().setSuccess(false).setMsg("审核失败");
        }
    }

    @Override
    public PageList<SearchMasterMsg> toHandle(SearchMasterMsgQuery query, HttpServletRequest request) {
        //判断当前登录人是平台管理员还是店铺管理员。如果是平台管理员还要设置shopId
        Logininfo logininfo = LoginContext.getLogininfo(request);
        Employee employee = employeeMapper.loadByLogininfoId(logininfo.getId());
        //根据emp中是否有shopid - 判断平台管理员还是店铺管理员
        //loginInfo里面的type - 判断用户或管理员
        if(employee.getShop_id()!=null){//店铺管理员
            query.setShopId(employee.getShop_id());
        }
        return super.queryPage(query);
    }

    //前端没有实现
    @Override
    public PageList<SearchMasterMsg> user(SearchMasterMsgQuery query, HttpServletRequest request) {
        //获取登录用户
        Logininfo logininfo = LoginContext.getLogininfo(request);
        User user = userMapper.loadByLogininfoId(logininfo.getId());
        //设置用户id
        query.setUserId(user.getId());
        //调用父类的分页查询方法：userId有值
        return super.queryPage(query);
    }

    @Override
    public void reject(Long id) {
        searchMasterMsgMapper.reject(id);
    }

    @Override
    public void accept(Map<String, String> map) {
        Long msgId = Long.parseLong(map.get("msgId"));
        Long empId = Long.parseLong(map.get("handler"));
        String note = map.get("note");
        //一：校验当前订单是否已经在处理
        OrderPetAcquisition order = orderPetAcquisitionMapper.loadByMsgId(msgId);
        //如果是待处理的订单，并且这个订单正在处理 - 不会生成新的订单
        if(order!=null && order.getState() == 0){//已经由订单 = 寻主消息正在处理
            throw new BusinessException("订单正在处理，请勿重复接单...");
        }

        //二：通过msgId生成宠物，录入到系统
        SearchMasterMsg msg = searchMasterMsgMapper.loadById(msgId);
        if (msg.getShop() == null) {
            msg.setShopId(employeeMapper.loadById(empId).getShop_id());
            searchMasterMsgMapper.update(msg);
        }
        searchMasterMsgMapper.update(msg);
        Pet pet = msg2Pet(msg);
        petMapper.save(pet);

        //三：生成收购订单
        OrderPetAcquisition orderTem = buildOrderPetAcquisition(msg,pet,empId,note);
        delayProduce.sendDelayMessage("delay-topic",orderTem.getSearchMasterMsgId().toString(),19);
        orderPetAcquisitionMapper.save(orderTem);

        //四：通过处理人去收回宠物
        //Employee employee = employeeMapper.loadById(empId);
        //SmsUtils.sendSms(employee.getPhone(),"你有新的订单，请及时处理，地址："+msg.getAddress());
        System.out.println("你有新的订单，请及时处理，地址："+msg.getAddress());
    }

    private OrderPetAcquisition buildOrderPetAcquisition(SearchMasterMsg msg, Pet pet, Long empId, String note) {
        OrderPetAcquisition order = new OrderPetAcquisition();
        String orderSn = CodeGenerateUtils.generateOrderSn(msg.getUserId());
        order.setOrderSn(orderSn);
        order.setDigest(msg.getName()+"收购订单");
        order.setLastcomfirmtime(new Date(System.currentTimeMillis() + 1000*60*60*24*2));
        order.setState(0);//待处理
        order.setPrice(msg.getPrice());
        //        order.setPaytype(); //现金支付
        order.setPetId(pet.getId());
        order.setUserId(msg.getUserId());
        order.setShopId(msg.getShopId());
        order.setAddress(msg.getAddress());
        order.setEmpId(empId);
        order.setSearchMasterMsgId(msg.getId());
        return order;
    }

    private Pet msg2Pet(SearchMasterMsg msg) {
        Pet pet = new Pet();
        pet.setName(msg.getName());
        pet.setCostprice(msg.getPrice());
        pet.setTypeId(msg.getPetType());
        pet.setResources(msg.getResources());
        pet.setState(0);
        pet.setShopId(msg.getShopId());
        pet.setUserId(msg.getUserId());
        pet.setSearchMasterMsgId(msg.getId());
        return pet;
    }

}
